<?php

namespace app\api\controller;

use app\api\logic\MiniAppWechat;
use app\basic\ApiController;
use hg\apidoc\annotation as Apidoc;
use support\Request;

/**
 * @Apidoc\Title("微信小程序")
 */
class MiniAppController extends ApiController
{
   protected $noNeedLogin = ['*'];

    public function __construct()
    {
        $this->logic = new MiniAppWechat();
        parent::__construct();
    }

    /**
     * @Apidoc\Title("小程序登录")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("code", type="string", require=true, desc="小程序登录凭证")
     * @Apidoc\Param("encryptedData", type="string", require=true, desc="小程序登录凭证")
     * @Apidoc\Param("iv", type="string", require=true, desc="小程序登录凭证")
     * @Apidoc\Returned("token", type="string", desc="token")
     */
    public function login(Request $request)
    {
        $code = $this->request->post('code');
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        $result = $this->logic->miniAppLogin($code,$encryptedData,$iv);
        // 如果返回的数据中有user_id  则直接登录
        if($result['user_id']){
            $ret = $this->auth->direct($result['user_id']);
            if($ret){
              $data = ['userinfo' => $this->auth->getUserinfo()];
              return $this->success('登录成功',$data);
            }
            return $this->fail('登录失败');
        }
        // 因为没有用户ID 需要发起注册
        $ret = $this->auth->register($result['username'], $result['password'], $result['mobile']);
        if($ret){
            $userinfo = $this->auth->getUserinfo();
            // 需要增加小程序登录的处理
            $result = $this->logic->setUserThird($userinfo,$result);
            if($result){
                $data = ['userinfo' => $userinfo];
                return $this->success('登录成功',$data);
            }
        }
        return $this->fail('登录失败');
    }


    /**
     * @Apidoc\Title("绑定openId")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("code", type="string", require=true, desc="小程序登录凭证")
     */
    public function bindingOpenid()
    {
        $code = $this->request->post('code');
        $user_id = $this->auth->getUserId();
        $result = $this->logic->getSession($code);
        // 如果返回的数据中有user_id  则直接登录
        if($result['user_id']!=$user_id){
            // 删除当前会员
            $this->auth->deleteUser($user_id);
            return $this->fail('注册失败,当前微信已绑定其他手机号');
        }
        // 需要增加小程序登录的处理
        $result = $this->logic->setUserThird(['id'=>$user_id],$result);
        if($result){
            return $this->success('绑定成功');
        }
        return $this->fail('绑定失败');
    }
}